package cn.ffcs.uec.staff.component;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.zkoss.zk.ui.Components;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.IdSpace;
import org.zkoss.zk.ui.SuspendNotAllowedException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zul.Div;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

import cn.ffcs.raptornuke.plugin.common.zk.util.ZkUtil;
import cn.ffcs.uec.common.manager.CustomFilesManager;
import cn.ffcs.uec.common.util.PermissionUtil;
import cn.ffcs.uec.organization.manager.UecOrgOrgsManager;
import cn.ffcs.uec.staff.component.bean.UecStaffInfoListboxBean;
import cn.ffcs.uec.staff.constant.UecStaffConstants;
import cn.ffcs.uec.staff.manager.UecStaffInfoManager;
import cn.ffcs.uec.staff.model.UecStaffInfo;
import cn.ffcs.uom.common.key.ActionKeys;
import cn.ffcs.uom.common.util.ApplicationContextUtil;
import cn.ffcs.uom.common.util.DateUtil;
import cn.ffcs.uom.common.util.IPortletInfoProvider;
import cn.ffcs.uom.common.util.ListboxUtils;
import cn.ffcs.uom.common.util.PlatformUtil;
import cn.ffcs.uom.common.util.PubUtil;
import cn.ffcs.uom.common.util.StrUtil;
import cn.ffcs.uom.common.vo.NodeVo;
import lombok.Getter;
import lombok.Setter;

@Controller
@Scope("prototype")
public class UecStaffInfoListboxExt extends Div implements IdSpace {

	private static final long serialVersionUID = -2212731640371254189L;

	/**
	 * 对应页面上的bean
	 */
	private UecStaffInfoListboxBean bean = new UecStaffInfoListboxBean();
	/**
	 * 人员基本信息对象
	 */
	private UecStaffInfo uecStaffInfo = new UecStaffInfo();
	/**
	 * 关闭窗口标志
	 */
	private Boolean onCloseFlag = true;

	/**
	 * 人员基本信息查询对象
	 */
	private UecStaffInfo qryUecStaffInfo;

	private UecStaffInfoManager uecStaffInfoManager = (UecStaffInfoManager) ApplicationContextUtil
			.getBean("uecStaffInfoManager");

	private UecOrgOrgsManager uecOrgOrgsManager = (UecOrgOrgsManager) ApplicationContextUtil
			.getBean("uecOrgOrgsManager");

	private CustomFilesManager customFilesManager = (CustomFilesManager) ApplicationContextUtil
			.getBean("customFilesManager");

	@Getter
	@Setter
	private IPortletInfoProvider portletInfoProvider;

	public UecStaffInfoListboxExt() {
		Executions.createComponents(UecStaffConstants.UEC_STAFF_INFO_EXT_LISTBOX_ZUL, this, null);
		Components.wireVariables(this, bean);
		Components.addForwards(this, this, '$');
		
		this.addForward("onSelectUecStaffInfoByGetOrgTree", this,
				"onSelectUecStaffInfoByGetOrgTreeResponse");
	}
	
	/**
	 * 监听事件
	 * @param event
	 * @throws Exception 
	 */
	public void onSelectUecStaffInfoByGetOrgTreeResponse(ForwardEvent event) throws Exception {
		uecStaffInfo = (UecStaffInfo) event.getOrigin().getData();
		if (null != uecStaffInfo) {
			this.bean.getHbox1().setVisible(false);
			qryUecStaffInfo = UecStaffInfo.newInstance();
			qryUecStaffInfo = uecStaffInfo;
			//queryStaffInfoAndGetView();
			PubUtil.fillBeanFromPo(uecStaffInfo, bean);
			groupDataTranslationDisplay();
		}
	}

	/**
	 * 初始化
	 */
	public void onCreate() {
		/**
		 * 判断用户是否是盟市主管 如果不是则隐藏查询控件
		 */
		String managerOrg = PermissionUtil.getManagerOrg();
		if (null == managerOrg) {
			bean.getConditionCaption().setVisible(false);
		}else {
			this.binListbox();
			this.setButtonValid(true, false, false);
		}
	}
	
	/**
	 * 关闭窗口事件
	 */
	public void onCloseWindown() {
		Events.postEvent("onCloseStaffMainWindown",this, onCloseFlag);
	}


	/**
	 * 绑定下拉框
	 */
	public void binListbox() {
		List<NodeVo> nodeVoList = new ArrayList<NodeVo>();
		String[][] option = { { "0", "人员姓名" }, { "1", "证件号码" }, { "2", "人员编码" } };
		for (int i = 0; i < option.length; i++) {
			NodeVo nodeVo = new NodeVo();
			for (int j = 0; j < 1; j++) {
				nodeVo.setId(option[i][j]);
				nodeVo.setName(option[i][j + 1]);
			}
			nodeVoList.add(nodeVo);
		}
		ListboxUtils.rendererForEdit(bean.getCondition(), nodeVoList);
	}

	/**
	 * 查询按钮
	 * 
	 * @throws Exception
	 */
	public void onQuery() throws Exception {
		setButtonValid(true, true, true);
		clearVariable();
		if (!StrUtil.isNullOrEmpty(bean.getCondition().getSelectedItem().getValue())
				&& !StrUtil.isNullOrEmpty(bean.getConditionValue().getValue())) {
			Listbox listbox = bean.getCondition();
			String listboxStr = (String) listbox.getSelectedItem().getValue();
			int listboxId = Integer.parseInt(listboxStr);
			qryUecStaffInfo = UecStaffInfo.newInstance();
			switch (listboxId) {
			case 0:
				qryUecStaffInfo.setName(bean.getConditionValue().getValue());
				break;
			case 1:
				qryUecStaffInfo.setIdNumber(bean.getConditionValue().getValue());
				break;
			case 2:
				qryUecStaffInfo.setCode(bean.getConditionValue().getValue());
			default:
				break;
			}
			UecStaffInfo findUecStaffInfo = uecStaffInfoManager.findUecStaffInfo(qryUecStaffInfo);
			if (null != findUecStaffInfo) {
				staffList();
			} else {
				ZkUtil.showError("无此人基本信息！", "提示信息");
			}

		}

	}

	/**
	 * 员工列表
	 * 
	 * @throws Exception
	 * @throws SuspendNotAllowedException
	 */
	public void staffList() throws SuspendNotAllowedException, Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("opType", "staffList");
		map.put("qryUecStaffInfo", qryUecStaffInfo);
		Window window = (Window) Executions.createComponents(UecStaffConstants.UEC_STAFF_LIST_ZUL, this, map);
		window.doModal();
		window.addEventListener("onOK", new EventListener() {
			@Override
			public void onEvent(Event event) throws Exception {
				if (event.getData() != null) {
					qryUecStaffInfo = (UecStaffInfo) event.getData();
					uecStaffInfo = qryUecStaffInfo;
					PubUtil.fillBeanFromPo(uecStaffInfo, bean);
					groupDataTranslationDisplay();
				}
			}
		});
	}

	/**
	 * 重置
	 * 
	 * @throws Exception
	 */
	public void onReset() throws Exception {
		clearVariable();
		bean.getConditionValue().setValue(null);
		PubUtil.clearComponent(this);
		Events.postEvent(UecStaffConstants.ON_CLEAN_TAB_UEC_STAFF_INFO_QUERY, this, uecStaffInfo);
		this.setButtonValid(true, false, false);
	}

	/**
	 * 清除变量
	 */
	public void clearVariable() {
		qryUecStaffInfo = null;
		uecStaffInfo = null;
	}

	/**
	 * 新增
	 * 
	 * @throws InterruptedException
	 * @throws Exception
	 */
	public void onAdd() throws InterruptedException, Exception {
		if (!PlatformUtil.checkPermissionDialog(getPortletInfoProvider(), ActionKeys.DATA_OPERATING)) {
			return;
		}
		this.addConfirm();
	}

	/**
	 * 新增前校验
	 * 
	 * @throws Exception
	 * @throws InterruptedException
	 */
	public void addConfirm() throws Exception, InterruptedException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("opType", "addConfirm");
		Window window = (Window) Executions.createComponents(UecStaffConstants.UEC_STAFF_INFO_ADDCONFIRM_ZUL, this,
				map);
		window.doModal();
		window.addEventListener("onOK", new EventListener() {
			@Override
			public void onEvent(Event event) throws Exception {
				if (event.getData() != null) {
					// Test
					qryUecStaffInfo = (UecStaffInfo) event.getData();
					PubUtil.fillBeanFromPo(qryUecStaffInfo, bean);
					uecStaffInfo = qryUecStaffInfo;
					groupDataTranslationDisplay();
				}
			}
		});

	}

	/**
	 * 删除
	 * 
	 * @throws Exception
	 */
	public void onDel() throws Exception {
		if (!PlatformUtil.checkPermissionDialog(getPortletInfoProvider(), ActionKeys.DATA_OPERATING)) {
			return;
		}
		if (this.uecStaffInfo != null && uecStaffInfo.getPkPsndoc() == null) {
			ZkUtil.showQuestion("确定要删除吗?", "提示信息", new EventListener() {
				public void onEvent(Event event) throws Exception {
					Integer result = (Integer) event.getData();
					if (result == Messagebox.OK) {
						uecStaffInfo.removeOnly();
						onReset();
					}
				}
			});
		} else {
			ZkUtil.showError("集团数据，禁止删除！", "提示信息");
		}
		this.setButtonValid(true, false, false);
	}

	/**
	 * 编辑
	 * 
	 * @throws Exception
	 */
	public void onEdit() throws Exception {
		if (!PlatformUtil.checkPermissionDialog(getPortletInfoProvider(), ActionKeys.DATA_OPERATING)) {
			return;
		}
		if (uecStaffInfo != null && uecStaffInfo.getPkPsndoc() == null) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("opType", "edit");
			map.put("uecStaffInfo", uecStaffInfo);
			Window window = (Window) Executions.createComponents(UecStaffConstants.UEC_STAFF_INFO_EDIT_ZUL, this, map);
			window.doModal();
			window.addEventListener("onOK", new EventListener() {
				@Override
				public void onEvent(Event event) throws Exception {
					if (event.getData() != null) {
						uecStaffInfo = (UecStaffInfo) event.getData();
						qryUecStaffInfo = uecStaffInfoManager.findUecStaffInfo(uecStaffInfo);
						PubUtil.fillBeanFromPo(qryUecStaffInfo, bean);
						uecStaffInfo = qryUecStaffInfo;
						groupDataTranslationDisplay();
					}
				}
			});
		} else {
			ZkUtil.showError("集团数据，禁止编辑！", "提示信息");
		}
		this.setButtonValid(true, true, true);
	}

	/**
	 * 设置按钮
	 * 
	 * @param canAdd
	 * @param candel
	 */
	private void setButtonValid(boolean canAdd, boolean canEdit, boolean canDel) {
		//this.bean.getAddButton().setDisabled(!canAdd);
		this.bean.getEditButton().setDisabled(!canEdit);
		//this.bean.getDelButton().setDisabled(!canDel);
	}

	/**
	 * 绑定bean 集团数据翻译展示,并向其他组件跑出事件
	 * 
	 * @throws Exception
	 */
	public void groupDataTranslationDisplay() throws Exception {
		if (null != uecStaffInfo) {
			// String类型日期转Date
			this.stringTransToDate();
			// 进入电信来源
			bean.getGlbdef2().setValue(customFilesManager.findCustomFilesByPkdefdoc(uecStaffInfo.getGlbdef2()));
			// 专业技术职务
			bean.getTitletechpost().setValue(customFilesManager.findCustomFilesByPkdefdoc(uecStaffInfo.getTitletechpost()));	
			// 职业资格
			bean.getProf().setValue(customFilesManager.findCustomFilesByPkdefdoc(uecStaffInfo.getProf()));
			// 民族
			bean.getNationality().setValue(customFilesManager.findCustomFilesByPkdefdoc(uecStaffInfo.getNationality()));
			// 婚姻状况
			bean.getMarital().setValue(customFilesManager.findCustomFilesByPkdefdoc(uecStaffInfo.getMarital()));
			// 健康状况
			bean.getHealth().setValue(customFilesManager.findCustomFilesByPkdefdoc(uecStaffInfo.getHealth()));
			// 政治面貌
			bean.getPolity().setValue(customFilesManager.findCustomFilesByPkdefdoc(uecStaffInfo.getPolity()));
			// 学历
			bean.getEdu().setValue(customFilesManager.findCustomFilesByPkdefdoc(uecStaffInfo.getEdu()));	
			// 学位	
			bean.getPkDegree().setValue(customFilesManager.findCustomFilesByPkdefdoc(uecStaffInfo.getPkDegree()));
			// 户口性质
			bean.getCharacterrpr().setValue(customFilesManager.findCustomFilesByPkdefdoc(uecStaffInfo.getCharacterrpr()));
			// 所属组织
			bean.getPkOrg().setValue(uecOrgOrgsManager.getUecOrgOrgsNameByPkOrg(uecStaffInfo.getPkOrg()));
			// 人力资源组织
			bean.getPkHrorg().setValue(uecOrgOrgsManager.getUecOrgOrgsNameByPkOrg(uecStaffInfo.getPkHrorg()));
			
			// 证件类型
			if (null != uecStaffInfo.getIdtype()) {
				Long idtype = uecStaffInfo.getIdtype();
				if (0L == idtype) {
					bean.getIdtype().setValue("身份证");
				} else {
					bean.getIdtype().setValue("");
				}
			}
			// 性别
			if (null != uecStaffInfo.getSex()) {
				Long sex = uecStaffInfo.getSex();
				if (sex == 1) {
					bean.getSex().setValue("男");
				} else if (sex == 2) {
					bean.getSex().setValue("女");
				} else {
					bean.getSex().setValue("");
				}
			}
			// 是否是历史成员
			if (null != uecStaffInfo.getIshiskeypsn()) {
				String ishiskeypsn = uecStaffInfo.getIshiskeypsn();
				if ("Y".equals(ishiskeypsn)) {
					bean.getIshiskeypsn().setValue("是");
				} else if ("N".equals(ishiskeypsn)) {
					bean.getIshiskeypsn().setValue("否");
				}
			}
			// 是否是门店营业员
			if (null != uecStaffInfo.getIsshopassist()) {
				String isshopassist = uecStaffInfo.getIsshopassist();
				if ("Y".equals(isshopassist)) {
					bean.getIsshopassist().setValue("是");
				} else if ("N".equals(isshopassist)) {
					bean.getIsshopassist().setValue("否");
				}
			}
			// 是否承包经营个人
			if (null != uecStaffInfo.getGlbdef14()) {
				String glbdef14 = uecStaffInfo.getGlbdef14();
				if ("Y".equals(glbdef14)) {
					bean.getGlbdef14().setValue("是");
				} else if ("N".equals(glbdef14)) {
					bean.getGlbdef14().setValue("否");
				}
			}
			// 启用状态
			if (null != uecStaffInfo.getEnablestate()) {
				Long enablestate = uecStaffInfo.getEnablestate();
				if (1L == enablestate) {
					bean.getEnablestate().setValue("未启用");
				} else if (2L == enablestate) {
					bean.getEnablestate().setValue("已启用");
				} else if (3L == enablestate) {
					bean.getEnablestate().setValue("已停用");
				} else {
					bean.getEnablestate().setValue("");
				}
			}
		}
		// 重要！！
		Events.postEvent(UecStaffConstants.ON_UEC_STAFF_INFO_QUERY, this, uecStaffInfo);
	}

	/**
	 * 将String类型的时间转换成Date类型
	 * 
	 * @throws ParseException
	 */
	public void stringTransToDate() throws ParseException {
		// 出生日期
		if (!StrUtil.isNullOrEmpty(uecStaffInfo.getBirthdate())) {
			bean.getBirthdate().setValue(DateUtil.patternStrToDate(uecStaffInfo.getBirthdate()));
		}
		// 入党(团)日期
		if (!StrUtil.isNullOrEmpty(uecStaffInfo.getJoinpolitydate())) {
			bean.getJoinpolitydate().setValue(DateUtil.patternStrToDate(uecStaffInfo.getJoinpolitydate()));
		}
		// 身故日期
		if (!StrUtil.isNullOrEmpty(uecStaffInfo.getDieDate())) {
			bean.getDieDate().setValue(DateUtil.patternStrToDate(uecStaffInfo.getDieDate()));
		}
		// 参加工作日期
		if (!StrUtil.isNullOrEmpty(uecStaffInfo.getJoinworkdate())) {
			bean.getJoinworkdate().setValue(DateUtil.patternStrToDate(uecStaffInfo.getJoinworkdate()));
		}
		// 离退休日期
		if (!StrUtil.isNullOrEmpty(uecStaffInfo.getRetiredate())) {
			bean.getRetiredate().setValue(DateUtil.patternStrToDate(uecStaffInfo.getRetiredate()));
		}
		// 预计退休日期
		if (!StrUtil.isNullOrEmpty(uecStaffInfo.getGlbdef15())) {
			bean.getGlbdef15().setValue(DateUtil.patternStrToDate(uecStaffInfo.getGlbdef15()));
		}
		// 进入电信系统日期
		if (!StrUtil.isNullOrEmpty(uecStaffInfo.getGlbdef3())) {
			bean.getGlbdef3().setValue(DateUtil.patternStrToDate(uecStaffInfo.getGlbdef3()));
		}
	}

}
